<?php
    defined('INDEX') or die ('Acesso direto n&atilde;o permitido');
    
    /**
     * This class is an interface for Doctrine build-models functions.
     * 
     * @author Carlos A. Junior
     */
	class DoctrineModelGenerator
	{
		public function __construct()
		{
			
		}
		
		private function deleteModelFiles (RecursiveDirectoryIterator $recursive, $directory)
		{
			while ($recursive->valid())
	    	{
	    		if(!$recursive->isDir() && !$recursive->isDot() && !preg_match('/svn/i', $recursive->getFilename()))
	    		{
	    			if(preg_match('/\.class\.php$/i', $recursive->getFilename()))
	    			{
	    				echo '<br/>removendo: '.$directory.$recursive->getFilename();
	    				unlink($directory.$recursive->getFilename());
	    			}
	    		}
	    		$recursive->next();
	    	}
		}
		
		/**
		 * This method creates all Classes of your database. This method needs
		 * the read and write permission in model/ directory to create all necessary
		 * files.
		 * After the all files be created this function add defined('INDEX') to protected
		 * the direct access to same.
		 * 
		 * @return void
		 */
		public function generateApplicationModelFromDatabase ()
		{
			require_once (dirname(__FILE__)."/../application/Application.class.php");
			$config = ApplicationFactory::getConfigurationFactory();
			try
			{
				echo '<br/>Iniciando a geração dos arquivos do modelo de negócio da aplicação.....';
				$connection = ApplicationFactory::getDoctrineConnectionFactory();
				
				if(is_dir($connection->getModelDirectory()))
				{
					if(is_readable($connection->getModelDirectory()))
					{
					    if(is_writable($connection->getModelDirectory()))
					    {
					    	set_time_limit(120);
					    	
					    	$recursive = new RecursiveDirectoryIterator($connection->getModelDirectory());
					    	
					    	$this->deleteModelFiles(new RecursiveDirectoryIterator($connection->getModelDirectory()), $connection->getModelDirectory());
					    	
					    	$options = array (
					    		'suffix' 				=> '.class.php',
					    		'baseClassesDirectory'  => 'base'
					    	);
					    	Doctrine::generateModelsFromDb($connection->getModelDirectory(), array(), $options);
					    	
					    	while ($recursive->valid())
					    	{
					    		// Remove directories and .svn files and folders.
					    		if(!$recursive->isDir() && !$recursive->isDot() && !preg_match('/svn/i', $recursive->getFilename()))
								{
									$filename = $connection->getModelDirectory().$recursive->getFilename();

									if(is_readable($filename) && is_writable($filename))
									{
										$content 	= file_get_contents($filename);
										$file 		= fopen($filename, 'w+');
										
										echo '<br/>'.$filename;
										
										$header = "<?php\n\n";
										$header.= "defined('INDEX') or die ('Acesso direto n&atilde;o permitido');\n\n";
										$header.= "require_once(dirname(__FILE__).'/base/Base".$recursive->getFilename()."');\n\n";
										
										$content = $header.str_replace('<?php', '', $content)."\n\n?>";
										
										fwrite($file, $content);
										fclose($file);
									}
									else
									{
										echo '<br/>nao..';
									}
								}
								
								$recursive->next();
					    	}
					    }
					    else
					    {
					    	die("<br/>O Diretório [".$connection->getModelDirectory()."] não possui permissão de escrita.");
					    }
					}
					else
					{
						die("<br/>O Diretório [".$connection->getModelDirectory()."] não possui permissão de leitura.");
					}
				}
				else
				{
					die("<br/>O Diretório [".$connection->getModelDirectory()."] não existe.");
				}
			} catch (Doctrine_Import_Builder_Exception $e) {
			    die("<br/>Falha ao gerar as classes do modelo da aplica&ccedil;&atilde;o. Mensagem: ".$e->getMessage());
			}
			
			echo '<br/>Arquivos do modelo de negócio gerados com sucesso!';
		}
		
	}
?>